package com.example.demo.controller;

import com.example.demo.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${loveWord.path}")
    private String basePath;

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        String s=name.charAt(0)+"\\";
        try {
            //输入流  通过输入流读取文件内容
            FileInputStream fileInputStream=new FileInputStream(new File(basePath+s+name));

            //输出流 通过浏览器将文件写回浏览器，在浏览器展示了图片
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("video/mpeg");

            int len=0;
            byte[] bytes=new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @PostMapping("/test")
    public R test(){
        /**
        测试R返回
         */
        //手动构造 user对象
        Map<String,Object> user=new HashMap<>();
        user.put("name","Tom");
        user.put("age",10);
        return R.success(user,"成功了！！！！！！");
    }

}
